﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using KingOfCSharp.iHunter;

namespace KingOfCSharp.iHunter.UI
{
    public partial class FolderTreeView : UserControl
    {
        public FolderTreeView()
        {
            InitializeComponent();
        }
        KingOfCSharp.iHunter.LocalClient client = null;


        public KingOfCSharp.iHunter.LocalClient Client
        {
            get
            {
                return client;
            }
            set
            {
                client = value;
                RefreshFolders();
            }
        }

        public void RefreshFolders()
        {
            if (client == null)
                return;

            this.treeView.BeginUpdate();
            this.treeView.Nodes.Clear();

            Guid oldGuid = SelectedFolderGuid;

            IFolder folder = client.RootFolder;
            TreeNode rootNode = this.treeView.Nodes.Add(folder.Guid.ToString(), folder.Name,0);
            rootNode.Tag = folder;
            RefreshChildNodes(rootNode, folder);
            this.SelectedFolderGuid = oldGuid;
            this.treeView.EndUpdate();
        }

        private void RefreshChildNodes(TreeNode parent, IFolder parentFolder)
        {
            foreach (IFolder child in parentFolder.SubFolders)
            {
                int imageIndex = 0;
                if (child.Name == "[Root]")
                {
                    imageIndex = 0;
                }
                else if (child.Name == "[Inbox]")
                {
                    imageIndex = 1;
                }
                else if (child.Name == "[Outbox]")
                {
                    imageIndex = 2;
                }
                else if (child.Name == "[Drafts]")
                {
                    imageIndex = 3;
                }
                else if (child.Name == "[Sent]")
                {
                    imageIndex = 4;
                }
                else if (child.Name == "[Deleted]")
                {
                    imageIndex = 5;
                }
                else if (child.Name == "[Spam]")
                {
                    imageIndex = 5;
                }
                else
                {
                    imageIndex = 6;
                }
                TreeNode node = parent.Nodes.Add(child.Guid.ToString(), child.Name, imageIndex,imageIndex);
                node.Tag = child;
                RefreshChildNodes(node, child);
            }
        }

        private IFolder GetAndCreateFolder(TreeNode node)
        {
            IFolder folder = node.Tag as IFolder;
            if (folder == null)
            {
                IFolder parent = GetAndCreateFolder(node.Parent);
                IFolder newFolder = new LocalFolder() {
                    Name = node.Text,
                    Settings = null,
                };

                Guid newGuid = client.NewFolder(newFolder, parent.Guid);
                foreach (IFolder item in parent.SubFolders)
                {
                    if (item.Guid == newGuid)
                    {
                        node.Tag = item;
                        node.Name = newGuid.ToString();
                        return item;
                    }
                }
            }

            return folder;
        }

        /*
        public IFolder SelectedFolder
        {
            get
            {
                TreeNode selNode = this.treeView.SelectedNode;
                if (selNode == null)
                    return null;

                return GetAndCreateFolder(selNode);
            }
        }
        */

        public IFolder GetAndCreateSelectedFolder()
        {
            TreeNode selNode = this.treeView.SelectedNode;
            if (selNode == null)
                return null;

            return GetAndCreateFolder(selNode);
        }

        public Guid SelectedFolderGuid
        {
            get
            {
                TreeNode selNode = this.treeView.SelectedNode;
                if (selNode == null || selNode.Tag == null)
                    return Guid.Empty;
                else
                    return (selNode.Tag as IFolder).Guid;
            }

            set
            {
                if (value == Guid.Empty)
                {
                    return;
                }

                TreeNode[] nodes = treeView.Nodes.Find(value.ToString(), true);
                if (nodes.Length > 0)
                {
                    this.treeView.SelectedNode = nodes[0];
                    nodes[0].Expand();
                    nodes[0].EnsureVisible();
                }
            }
        }

        public bool Selected
        {
            get
            {
                return treeView.SelectedNode != null;
            }
        }

        public bool IsSelectedFolderChildOf(IFolder folder)
        {
            if (treeView.SelectedNode == null)
            {
                return false;
            }

            for (TreeNode pp = treeView.SelectedNode; pp != null; pp = pp.Parent)
            {
                if (pp.Tag == folder)
                {
                    return true;
                }
            }

            return false;
        }

        private void treeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Label != null && e.Node.Text != e.Label && !IsNewFolderNameValid(e.Node.Parent, e.Label))
            {
                e.CancelEdit = true;
                MessageBox.Show("Cannot rename folder: the folder name is invalid or it already exists.",
                    "Error Renaming Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Node.BeginEdit();
            }
        }

        private void treeView_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Node.Tag != null)
            {
                e.CancelEdit = true;
                return;
            }
        }

        private bool IsNewFolderNameValid(TreeNode parent, string name)
        {
            if (name == null || name.Length == 0)
            {
                return false;
            }

            foreach (TreeNode node in parent.Nodes)
            {
                if (node.Text == name)
                {
                    return false;
                }
            }

            return true;
        }

        private string GenerateValidFolderName(TreeNode parent)
        {
            string baseName = "New Folder";
            if (IsNewFolderNameValid(parent, baseName))
            {
                return baseName;
            }

            for (int i = 2; true; ++i)
            {
                string name = string.Format("{0} ({1})", baseName, i);
                if (IsNewFolderNameValid(parent, name))
                {
                    return name;
                }
            }
        }

        private void createSubFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeView.SelectedNode;
            if (node == null)
            {
                return;
            }

            TreeNode subNode = node.Nodes.Add(GenerateValidFolderName(node));
            subNode.ImageIndex = 7;
            treeView.SelectedImageIndex = 7;
            treeView.SelectedNode = subNode;
            subNode.BeginEdit();
        }

        private void treeView_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                treeView.SelectedNode = treeView.GetNodeAt(e.X, e.Y);
                renameToolStripMenuItem.Enabled = (treeView.SelectedNode.Tag == null);
            }
        }

        private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView.SelectedNode.BeginEdit();
        }
    }
}
